import 'package:flutter/material.dart';
import 'package:imath/models/question.dart';
import 'package:imath/math/math_cell.dart';
import 'image_viewer.dart';

// 题目显示模式枚举
enum QuestionMode {
  reading, // 阅读模式
  answering, // 答题模式
}

class QuestionView extends StatefulWidget {
  final Question question;
  final QuestionMode mode;

  const QuestionView({
    super.key,
    required this.question,
    required this.mode,
  });

  @override
  State<QuestionView> createState() => _QuestionViewState();
}

class _QuestionViewState extends State<QuestionView> {
  // 答题模式下记录用户选择的答案
  String? selectedAnswer;

  @override
  Widget build(BuildContext context) {
    if (widget.question.title == null || widget.question.content == null) {
      return const Card(
        child: ListTile(
          title: Text('无效的题目数据'),
        ),
      );
    }

    List<String> imageUrls = _parseImageUrls(widget.question.qImages);
    bool isChoice = isChoiceQuestion(widget.question);
    final content = widget.question.content!.trim() + '\n';

    return SingleChildScrollView(
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisSize: MainAxisSize.min,
          children: [
            // 题目标题
            ConstrainedBox(
              constraints: const BoxConstraints(
                minWidth: 0,
                maxWidth: double.infinity,
                minHeight: 0,
                maxHeight: double.infinity,
              ),
              child: MathCell(
                content: widget.question.title ?? '',
                textStyle:
                    const TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
              ),
            ),
            const SizedBox(height: 8),

            // 题目内容
            ConstrainedBox(
              constraints: const BoxConstraints(
                minWidth: 0,
                maxWidth: double.infinity,
                minHeight: 0,
                maxHeight: double.infinity,
              ),
              child: MathCell(
                content: content,
                textStyle: const TextStyle(fontSize: 18),
              ),
            ),
            const SizedBox(height: 8),

            // 图片位置：选择题放在题干和选项之间，非选择题放在题目下方
            if (imageUrls.isNotEmpty && isChoice)
              _buildQuestionImages(imageUrls),

            // 选项内容（如果有的话）
            if (widget.question.options != null &&
                widget.question.options!.isNotEmpty)
              _buildOptionsDisplay(
                  _parseOptionsWithImages(widget.question.options!)),

            // 图片位置：非选择题放在题目下方
            const SizedBox(height: 8),
            if (imageUrls.isNotEmpty && !isChoice)
              _buildQuestionImages(imageUrls),
          ],
        ),
      ),
    );
  }

  // 构建选项显示组件
  Widget _buildOptionsDisplay(List<OptionItem> options) {
    if (options.isEmpty) {
      return const SizedBox.shrink();
    }

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisSize: MainAxisSize.min,
      children: options.map((option) {
        return Padding(
          padding: const EdgeInsets.symmetric(vertical: 4.0),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 答题模式下的圆圈选择器（仅对选择题有效）
              if (widget.mode == QuestionMode.answering &&
                  isChoiceQuestion(widget.question))
                _buildAnswerSelector(option.label),

              // 选项标识符
              Text(
                '${option.label}. ',
                style: const TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.w500,
                ),
              ),
              // 选项内容
              Expanded(
                child: option.isImage
                    ? _buildImageOption(option)
                    : ConstrainedBox(
                        constraints: const BoxConstraints(
                          minWidth: 0,
                          maxWidth: double.infinity,
                          minHeight: 0,
                          maxHeight: double.infinity,
                        ),
                        child: MathCell(content: option.content),
                      ),
              ),
            ],
          ),
        );
      }).toList(),
    );
  }

  // 构建答题模式下的答案选择器
  Widget _buildAnswerSelector(String optionLabel) {
    bool isSelected = selectedAnswer == optionLabel;

    return GestureDetector(
      onTap: () {
        setState(() {
          selectedAnswer = isSelected ? null : optionLabel;
        });
      },
      child: Container(
        width: 24,
        height: 24,
        margin: const EdgeInsets.only(right: 8, top: 2),
        decoration: BoxDecoration(
          shape: BoxShape.circle,
          border: Border.all(
            color: isSelected ? Colors.blue : Colors.grey,
            width: 2,
          ),
          color: isSelected ? Colors.blue : Colors.transparent,
        ),
        child: isSelected
            ? const Icon(
                Icons.check,
                size: 16,
                color: Colors.white,
              )
            : null,
      ),
    );
  }

  // 构建图片选项
  Widget _buildImageOption(OptionItem option) {
    return GestureDetector(
      onTap: () => _showImageDialog(option.imageUrl!),
      child: Image.network(
        option.imageUrl!,
        fit: BoxFit.contain,
        loadingBuilder: (context, child, loadingProgress) {
          if (loadingProgress == null) return child;
          return Container(
            height: 100,
            color: Colors.grey[200],
            child: Center(
              child: CircularProgressIndicator(
                value: loadingProgress.expectedTotalBytes != null
                    ? loadingProgress.cumulativeBytesLoaded /
                        loadingProgress.expectedTotalBytes!
                    : null,
              ),
            ),
          );
        },
        errorBuilder: (context, error, stackTrace) {
          return Container(
            height: 100,
            color: Colors.grey[200],
            child: const Center(
              child: Icon(
                Icons.broken_image,
                color: Colors.grey,
                size: 30,
              ),
            ),
          );
        },
      ),
    );
  }

  // 判断是否为选择题
  bool isChoiceQuestion(Question question) {
    // 根据题目类型或选项内容判断是否为选择题
    if (question.type != null) {
      final type = question.type!.toLowerCase();
      return type.contains('选择') ||
          type.contains('单选') ||
          type.contains('多选') ||
          type.contains('choice') ||
          type.contains('select');
    }

    // 如果类型字段为空，根据选项内容判断
    if (question.options != null && question.options!.isNotEmpty) {
      final options = question.options!;
      // 检查是否包含选项标识符（A、B、C、D等）
      return RegExp(r'[A-D][\s\.、]').hasMatch(options);
    }

    return false;
  }

  // 获取用户选择的答案（仅在答题模式下有效）
  String? getSelectedAnswer() {
    return widget.mode == QuestionMode.answering ? selectedAnswer : null;
  }

  // 重置选择（仅在答题模式下有效）
  void resetSelection() {
    if (widget.mode == QuestionMode.answering) {
      setState(() {
        selectedAnswer = null;
      });
    }
  }

  // 解析图片URL字符串，返回URL列表
  List<String> _parseImageUrls(String? imagesString) {
    if (imagesString == null || imagesString.trim().isEmpty) {
      return [];
    }

    // 按逗号分割，并去除空白字符
    return imagesString
        .split(',')
        .map((url) => url.trim())
        .where((url) => url.isNotEmpty)
        .toList();
  }

  // 构建题目图片显示组件
  Widget _buildQuestionImages(List<String> imageUrls) {
    if (imageUrls.isEmpty) {
      return const SizedBox.shrink();
    }
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisSize: MainAxisSize.min,
      children: [
        const SizedBox(height: 8),
        if (imageUrls.length == 1)
          _buildImageItem(imageUrls.first)
        else
          // 多张图片时使用Column布局，避免ListView的约束问题
          ...imageUrls.asMap().entries.map((entry) {
            int index = entry.key;
            String imageUrl = entry.value;
            return Column(
              children: [
                _buildImageItem(imageUrl),
                if (index < imageUrls.length - 1) const SizedBox(height: 8),
              ],
            );
          }).toList(),
      ],
    );
  }

  // 构建单个图片项
  Widget _buildImageItem(String imageUrl) {
    return GestureDetector(
      onTap: () => _showImageDialog(imageUrl),
      child: ConstrainedBox(
        constraints: const BoxConstraints(
          maxHeight: 300, // 设置最大高度，避免图片过大
          minHeight: 100, // 设置最小高度，确保加载状态有足够空间
        ),
        child: Image.network(
          imageUrl,
          fit: BoxFit.contain, // 保持宽高比，确保图片完整显示
          loadingBuilder: (context, child, loadingProgress) {
            if (loadingProgress == null) return child;
            return Container(
              height: 140, // 保持原有的高度设置
              color: Colors.grey[200],
              child: Center(
                child: CircularProgressIndicator(
                  value: loadingProgress.expectedTotalBytes != null
                      ? loadingProgress.cumulativeBytesLoaded /
                          loadingProgress.expectedTotalBytes!
                      : null,
                ),
              ),
            );
          },
          errorBuilder: (context, error, stackTrace) {
            return Container(
              height: 140, // 保持原有的高度设置
              color: Colors.grey[200],
              child: const Center(
                child: Icon(
                  Icons.broken_image,
                  color: Colors.grey,
                  size: 40,
                ),
              ),
            );
          },
        ),
      ),
    );
  }

  // 显示图片放大对话框
  void _showImageDialog(String imageUrl) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return Dialog(
          backgroundColor: Colors.transparent,
          child: Stack(
            children: [
              // 背景遮罩
              GestureDetector(
                onTap: () => Navigator.of(context).pop(),
                child: Container(
                  color: Colors.black.withOpacity(0.8),
                ),
              ),
              // 图片内容
              Center(
                child: Container(
                  margin: const EdgeInsets.all(20),
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(8),
                    boxShadow: [
                      BoxShadow(
                        color: Colors.black.withOpacity(0.3),
                        blurRadius: 10,
                        spreadRadius: 2,
                      ),
                    ],
                  ),
                  child: ClipRRect(
                    borderRadius: BorderRadius.circular(8),
                    child: Image.network(
                      imageUrl,
                      fit: BoxFit.contain,
                      loadingBuilder: (context, child, loadingProgress) {
                        if (loadingProgress == null) return child;
                        return Container(
                          width: 300,
                          height: 300,
                          color: Colors.white,
                          child: Center(
                            child: CircularProgressIndicator(
                              value: loadingProgress.expectedTotalBytes != null
                                  ? loadingProgress.cumulativeBytesLoaded /
                                      loadingProgress.expectedTotalBytes!
                                  : null,
                            ),
                          ),
                        );
                      },
                      errorBuilder: (context, error, stackTrace) {
                        return Container(
                          width: 300,
                          height: 300,
                          color: Colors.white,
                          child: const Center(
                            child: Column(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                Icon(
                                  Icons.broken_image,
                                  color: Colors.grey,
                                  size: 60,
                                ),
                                SizedBox(height: 16),
                                Text(
                                  '图片加载失败',
                                  style: TextStyle(
                                    color: Colors.grey,
                                    fontSize: 16,
                                  ),
                                ),
                              ],
                            ),
                          ),
                        );
                      },
                    ),
                  ),
                ),
              ),
              // 关闭按钮
              Positioned(
                top: 40,
                right: 20,
                child: GestureDetector(
                  onTap: () => Navigator.of(context).pop(),
                  child: Container(
                    padding: const EdgeInsets.all(8),
                    decoration: BoxDecoration(
                      color: Colors.black.withOpacity(0.6),
                      shape: BoxShape.circle,
                    ),
                    child: const Icon(
                      Icons.close,
                      color: Colors.white,
                      size: 24,
                    ),
                  ),
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  // 解析选项中的图片，返回选项列表，每个选项包含选项标识符和图片URL（如果有的话）
  List<OptionItem> _parseOptionsWithImages(String lineStr) {
    List<OptionItem> options = [];
    // 按换行符分割选项
    List<String> optionLines = lineStr
        .split(RegExp(r'\r\n|\n|\\n|[;,]'))
        .where((line) => line.trim().isNotEmpty)
        .toList();

    for (String line in optionLines) {
      line = line.trim();
      if (line.isEmpty) continue;

      RegExp optionRegex =
          RegExp(r'^([A-F]|[①②③④⑤⑥⑦⑧]|\([A-Z]\))[\.、\s]\s*(.*)$');
      RegExp urlRegex = RegExp(r'^(https?://).*');
      Match? match = optionRegex.firstMatch(line);

      if (match != null) {
        String optionLabel = match.group(1)!;
        String content = match.group(2)!;

        // 检查内容是否包含markdown图片格式
        RegExp imageRegex = RegExp(r'!\[([^\]]*)\]\(([^)]+)\)');
        Match? imageMatch = imageRegex.firstMatch(content);

        // 检查内容是否包含HTTP/HTTPS URL（可能前面有数字或其他字符）
        Match? urlMatch = urlRegex.firstMatch(content);

        if (imageMatch != null) {
          // 包含markdown图片格式的选项
          String imageUrl = imageMatch.group(2)!;
          options.add(OptionItem(
            label: optionLabel,
            content: content,
            imageUrl: imageUrl,
            isImage: true,
          ));
        } else if (urlMatch != null) {
          // 包含HTTP/HTTPS URL的选项（如：① https://example.com/image.jpg）
          String imageUrl = urlMatch.group(0)!;
          options.add(OptionItem(
            label: optionLabel,
            content: content,
            imageUrl: imageUrl,
            isImage: true,
          ));
        } else {
          // 普通文本选项
          options.add(OptionItem(
            label: optionLabel,
            content: content,
            imageUrl: null,
            isImage: false,
          ));
        }
      }
    }

    return options;
  }
}
